package com.study.modules.saas.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.study.Util.PasswordUtil;
import com.study.common.constants.RedisCache;
import com.study.common.BusinessException;
import com.study.Util.IDUtil;
import com.study.modules.saas.repository.dao.UserDao;
import com.study.modules.saas.repository.enums.UserStatus;
import com.study.modules.saas.repository.model.RoleDO;
import com.study.modules.saas.repository.model.UserDO;
import com.study.security.domain.CurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisCache redisCache;

    @Autowired
    RoleService roleService;


    public CurrentUser longin(String username, String password) {

        log.info("登录service:开始");

        if (StringUtils.isAnyEmpty(username, password)) {
            throw new BusinessException("用户名密码为空");
        }

        UserDO userDO = this.getUserByUserName(username);

        if (ObjectUtil.isNull(userDO)) {
            throw new BusinessException("用户名不存在");
        }

        if (!StringUtils.equals(userDO.getPassWord(), PasswordUtil.encodedPassWord(password))) {
            throw new BusinessException("密码错误");
        }

        if (UserStatus.DISABLE.equals(userDO.getStatus())) {
            throw new BusinessException("账号已被禁用");
        }

        if (ObjectUtil.isNotNull(userDO.getDeletedAt())) {
            throw new BusinessException("用户已被删除");
        }

        String uuid = userDO.getUuid();
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(uuid, uuid);
        try {
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            CurrentUser currentUser = (CurrentUser) authenticate.getPrincipal();

            userDao.updateUserLastLoginTime(uuid);
            return currentUser;
        } catch (Exception e) {
            log.info("登录认证失败");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * uuid 查找用户
     *
     * @param uuid
     * @return
     */
    public UserDO getUserByUuid(String uuid) {
        UserDO userDO = userDao.selectOne(new LambdaQueryWrapper<UserDO>()
                .eq(UserDO::getUuid, uuid)
                .isNull(UserDO::getDeletedAt));
        if (ObjectUtil.isNotNull(userDO)) {
            RoleDO roleDO = roleService.getRoleByUuid(uuid);
            if (ObjectUtil.isNotNull(roleDO)) {
                userDO.setRoleDO(roleDO);
            }
        }
        return userDO;
    }

    /**
     * 用户名查找
     *
     * @param userName
     * @return
     */
    public UserDO getUserByUserName(String userName) {
        UserDO userDO = userDao.selectOne(new LambdaQueryWrapper<UserDO>().eq(UserDO::getUserName, userName));
        return userDO;
    }

    /**
     * 用户名推荐手机号
     *
     * @param username
     * @param password
     */
    public void register(String username, String password) {

        if (StringUtils.isAnyBlank(username, password) && StringUtils.isAnyBlank(username, password)) {
            throw new BusinessException("用户名密码为空！");
        }
        UserDO userDO = this.getUserByUserName(username);

        if (ObjectUtil.isNotNull(userDO)) {
            throw new BusinessException("用户名已存在");
        }
        userDO = new UserDO();
        userDO.setUuid(IDUtil.randomUUID());
        userDO.setUserName(username);
        userDO.setPassWord(PasswordUtil.encodedPassWord(password));
        userDO.setCreatedAt(new Date());
        userDao.insert(userDO);
    }


    /**
     * 从缓存中获取currentUser
     *
     * @param token
     * @return
     */
    public CurrentUser getCurrentUserByToken(String token) {
        String uuid = redisCache.getUserToken(token);
        if (StringUtils.isNotBlank(uuid)) {
            String currentUser = redisCache.getCurrentUser(uuid);
            if (StringUtils.isNotBlank(currentUser)) {
                return JSON.parseObject(currentUser, CurrentUser.class);
            }
        }
        return null;
    }


    /**
     * 退出登录
     *
     * @param token
     * @return
     */
    public CurrentUser logOut(String token){
        String uuid = redisCache.getUserToken(token);
        if (StringUtils.isNotBlank(uuid)) {
            redisCache.deletedUserToken(token);
            String currentUser = redisCache.getCurrentUser(uuid);
            if (StringUtils.isNotBlank(currentUser)) {
                redisCache.deletedCurrentUser(uuid);
                return JSON.parseObject(currentUser, CurrentUser.class);
            }
        }
        return null;
    }

}
